from django.utils import timezone
from .models import Payment
from orders.models import Order
from decimal import Decimal
import uuid

class PaymentService:
    """支付业务逻辑服务类"""
    
    @staticmethod
    def create_payment(order_id, payment_method, amount, user):
        """创建支付记录"""
        try:
            order = Order.objects.get(id=order_id, customer=user)
        except Order.DoesNotExist:
            raise ValueError('订单不存在或无权操作')
        
        # 检查订单状态
        if order.status != 'created':
            raise ValueError('订单状态不允许支付')
        
        # 创建支付记录
        payment = Payment.objects.create(
            order=order,
            payment_method=payment_method,
            amount=Decimal(str(amount)),
            status='pending',
            transaction_id=str(uuid.uuid4()).replace('-', '')[:32]  # 生成交易ID
        )
        
        return payment
    
    @staticmethod
    def process_wechat_payment(order_id, user):
        """处理微信支付"""
        payment = PaymentService.create_payment(
            order_id=order_id,
            payment_method='wechat',
            amount=Order.objects.get(id=order_id).final_price,
            user=user
        )
        
        # 这里应该调用微信支付API，生成预支付订单
        # 为简化示例，我们直接返回模拟数据
        prepay_data = {
            'appId': 'your_app_id',
            'timeStamp': str(int(timezone.now().timestamp())),
            'nonceStr': str(uuid.uuid4()).replace('-', '')[:32],
            'package': f'prepay_id=wx201410272009395522657a690389285100',
            'signType': 'MD5'
        }
        
        return payment, prepay_data
    
    @staticmethod
    def process_balance_payment(order_id, user):
        """处理余额支付"""
        # 检查用户余额
        from wallet.models import Wallet
        try:
            wallet = Wallet.objects.get(user=user)
        except Wallet.DoesNotExist:
            raise ValueError('钱包不存在')
        
        order = Order.objects.get(id=order_id)
        if wallet.balance < order.final_price:
            raise ValueError('余额不足')
        
        # 创建支付记录
        payment = PaymentService.create_payment(
            order_id=order_id,
            payment_method='balance',
            amount=order.final_price,
            user=user
        )
        
        # 扣除余额
        wallet.balance -= order.final_price
        wallet.save()
        
        # 更新支付状态
        payment.status = 'completed'
        payment.paid_at = timezone.now()
        payment.save()
        
        # 更新订单状态
        order.status = 'paid'
        order.paid_at = timezone.now()
        order.save()
        
        return payment
    
    @staticmethod
    def handle_payment_notification(transaction_id, payment_status, **kwargs):
        """处理支付通知"""
        try:
            payment = Payment.objects.get(transaction_id=transaction_id)
        except Payment.DoesNotExist:
            raise ValueError('支付记录不存在')
        
        # 更新支付状态
        payment.status = payment_status
        if payment_status == 'completed':
            payment.paid_at = timezone.now()
        payment.save()
        
        # 如果支付成功，更新订单状态
        if payment_status == 'completed':
            order = payment.order
            order.status = 'paid'
            order.paid_at = timezone.now()
            order.save()
        
        return payment